﻿using System;
using System.Collections.Generic;
using System.Text;
using WLMCoreLibrary;
using System.Data;
using System.Data.Odbc;
using System.Web.UI.WebControls;


namespace SAW_Core
{
    public class RibbonMenu : BaseClass
    {

        #region public properties
        public int orden { get; set; }
        public int idParent { get; set; }
        public Boolean inOrb { get; set; }
        public String Caption { get; set; }
        public String Icono { get; set; }
        public String Relacion { get; set; }
        public String Descripcion { get; set; }
        public String OnClick { get; set; }
        public String OnOver { get; set; }
        public String OnOut { get; set; }
        #endregion

        #region constructors
        public RibbonMenu(bool Create, ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            if (Create)
            {

                WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
                id = classBinder.NewRecord("RIBBONMENU");
                string queryString = "";
                queryString = "SELECT * FROM RIBBONMENU WHERE id='" + this.id + "'";
                GetRecord(queryString);
            }
        }

        public RibbonMenu(int registryId, ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
            queryString = "SELECT * FROM RIBBONMENU WHERE id='" + registryId + "'";

            this.GetRecord(queryString);
        }
        #endregion

        #region public methods

        public void Save()
        {
            UpdateBind();
        }

        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM RIBBONMENU WHERE id='" + this.id + "'";
            ConexionDBInterna.ExecuteCommand(queryString);

        }

        public string GenerarMenu(int idOpcion, int profundidad, string MenuName, string catBehind)
        {

            string strCommand;
            //string cadena;
            int x = 2;
            StringBuilder salida = new StringBuilder();
            //if (HttpContext.Current.Application["MenuPrincipal"] == null)
            //{
            strCommand = "SELECT * from RIBBONMENU WHERE idParent=" + idOpcion + " ORDER BY orden";

            OdbcDataReader registro = ConexionDBInterna.ExecuteReader(strCommand);
            Boolean tieneHijos = false;
            Boolean primerHijo = true;
            while (registro.Read())
            {
                string accion = "";
                switch (profundidad)
                {

                    case 0:
                        salida.Append("<li><a href=\"javascript:void(0);\" accesskey=\"" + x + "\" id=\"PestanaPanel" + registro["caption"] + "\" onclick=\"mostrarPanel('" + registro["caption"] + "');\">" + registro["caption"] + "</a>\n<ul> \n");
                        break;
                    case 1:
                        salida.Append("<li> \n <h2><span>" + registro["caption"] + "</span></h2>\n");
                        break;
                    case 2:
                        strCommand = "SELECT * from RIBBONMENU WHERE idParent=" + registro["id"] + " ORDER BY orden";
                        OdbcDataReader registroHijos = ConexionDBInterna.ExecuteReader(strCommand);
                        if (registroHijos.HasRows)
                        {
                            salida.Append("<div class=\"ribbon-list\">");
                            tieneHijos = true;
                        }
                        else
                        {
                            string tipoOpcion = "BotonControl";
                            //if(primerHijo)
                            //{
                            //    tipoOpcion="BotonControl1";
                            //    primerHijo=false;
                            //}


                            if (registro["onClick"].ToString() != "")
                                accion = registro["onclick"].ToString();
                            else
                                accion = "RibbonMenuBoton(this);";

                            salida.Append("<div class='" + tipoOpcion + "' onclick=\"" + accion + "\" onmouseout=\"" + registro["onOut"] + "\" onmouseover=\"" + registro["onOver"] + "\"  title=\"" + registro["descripcion"] + "\" rel=\"" + registro["relacion"] + "\"> \n     <img src=\"" + registro["icono"] + "\" /> \n " + registro["caption"] + " </div>\n\n ");
                        }
                        break;
                    case 3:

                        if (registro["onClick"].ToString() != "")
                            accion = registro["onclick"].ToString();
                        else
                            accion = "RibbonMenuBoton(this);";
                        string iconito = "";
                        if (registro["icono"].ToString() != "")
                            iconito = "<img src=\"" + registro["icono"] + "\" />";
                        salida.Append("<div class='BotonControl' onclick=\"" + accion + "\" onmouseout=\"" + registro["onOut"] + "\" onmouseover=\"" + registro["onOver"] + "\"  title=\"" + registro["descripcion"] + "\" rel=\"" + registro["relacion"] + "\"> \n     " + iconito + " \n " + registro["caption"] + " </div>\n\n");

                        break;
                }
                x++;
                string catName = "";//tituloaPostName(registro["nombre"].ToString());

                //salida.Append("<li><a href=\"/informacion/" + catBehind + catName.ToLower() + ".aspx\"><span>" + registro["nombre"] + "</span></a>");


                salida.Append(GenerarMenu(Convert.ToInt32(registro["id"]), profundidad + 1, MenuName, catBehind + catName + "/"));

                switch (profundidad)
                {
                    case 0:
                        salida.Append("</ul>\n </li>\n ");
                        break;
                    case 1:
                        salida.Append("</li>\n");
                        break;
                    case 2:
                        if (tieneHijos)
                            salida.Append("</div>");

                        break;
                    case 3:

                        break;
                }
            }


            registro = null;
            //if (profundidad == 0)
            //    HttpContext.Current.Application["MenuPrincipal"] = salida.ToString();
            //else
            return salida.ToString();

            //}
            //    return "<ul id=\"" + MenuName + "\" >\n" + HttpContext.Current.Application["MenuPrincipal"].ToString() + "</ul>\n";

        }

        public string GenerarPaneles()
        {
            StringBuilder salida = new StringBuilder();
            string strCommand = "SELECT * from RIBBONMENU WHERE idParent=1 ORDER BY orden";
            OdbcDataReader registro = ConexionDBInterna.ExecuteReader(strCommand);

            while (registro.Read())
            {
                salida.Append("<div class=\"Contenido\" id=\"PanelDiv" + registro["caption"] + "\"><div id=\"Div" + registro["caption"] + "\"></div></div>\n ");
            }

            return salida.ToString();
        }

        public string GenerarScriptPaneles()
        {
            StringBuilder matriz = new StringBuilder();
            StringBuilder lista = new StringBuilder();
            lista.Append("var listaPaneles = [");
            matriz.Append("var panelMatrix = [\n");
            string strCommand = "SELECT * from RIBBONMENU WHERE idParent=1 ORDER BY orden";
            OdbcDataReader registro = ConexionDBInterna.ExecuteReader(strCommand);
            int x = 1;
            while (registro.Read())
            {
                matriz.Append("['" + registro["caption"] + "', false, '" + registro["relacion"] + "']");
                lista.Append("'" + registro["caption"] + "'");
                if (x < registro.RecordsAffected)
                {
                    x++;
                    matriz.Append(",\n");
                    lista.Append(",");
                }
            }
            matriz.Append("];\n\n\n");
            lista.Append("];\n");
            return "<script language=\"javascript\" type=\"text/javascript\">\n" + lista.ToString() + matriz.ToString() + "\n</script>\n\n";
        }

        public TreeNodeCollection CreateTreeNodes(int idCategoria, int profundidad, string comportamiento, int selectedNode, string NombreArbol)
        {
            StringBuilder salidaFuncion = new StringBuilder();
            string strCommand = "SELECT * FROM ribbonmenu WHERE idParent='" + idCategoria.ToString() + "' ORDER BY orden";
            OdbcDataReader registro = ConexionDBInterna.ExecuteReader(strCommand);

            TreeNodeCollection listaNodos = new TreeNodeCollection();
            //if (registro.HasRows)
            //{
            //    //if (profundidad == 0)
            //    //{
            //    //    TreeNode nodo= new TreeNode(
            //    //    //salidaFuncion.Append("<script type=\"text/javascript\">\n function seleccionNodo(idNodo) \n{\n" + comportamiento + "}\n arbol = new dTree('arbol');arbol.add(" + idCategoria + ",-1,'" + NombreArbol + "','javascript: void(0);');\n");

            //    //}
            //}
            while (registro.Read())
            {
                //salidaFuncion.Append("arbol.add(" + registro["id"] + "," + idCategoria + ",'" + registro["nombre"] + "','javascript:seleccionNodo(" + registro["id"].ToString() + ");');" + CreateTree(Convert.ToInt32(registro["id"]), (profundidad + 1), comportamiento, selectedNode, NombreArbol));
                TreeNode nodo = new TreeNode(registro["caption"].ToString(), registro["id"].ToString());
                TreeNodeCollection arbol = new TreeNodeCollection();
                arbol = CreateTreeNodes(Convert.ToInt32(registro["id"]), (profundidad + 1), comportamiento, selectedNode, NombreArbol);
                foreach (TreeNode nodohijo in arbol)
                    nodo.ChildNodes.Add(nodohijo);
                listaNodos.Add(nodo);

            }
            //if (profundidad == 0)
            //{
            //    salidaFuncion.Append("arbol.selectedNode=" + selectedNode + ";  </script>");

            //}

            registro.Close();
            registro = null;
            return listaNodos;
        }

        #endregion

        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]); if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];


                if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
                    idUsuario = (System.Int32)reader["idUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("orden")))
                    orden = (System.Int32)reader["orden"];
                if (!reader.IsDBNull(reader.GetOrdinal("idParent")))
                    idParent = (System.Int32)reader["idParent"];
                if (!reader.IsDBNull(reader.GetOrdinal("inOrb")))
                    inOrb = Convert.ToBoolean(reader["inOrb"]);
                if (!reader.IsDBNull(reader.GetOrdinal("Caption")))
                    Caption = (System.String)reader["Caption"];
                if (!reader.IsDBNull(reader.GetOrdinal("Icono")))
                    Icono = (System.String)reader["Icono"];
                if (!reader.IsDBNull(reader.GetOrdinal("Relacion")))
                    Relacion = (System.String)reader["Relacion"];
                if (!reader.IsDBNull(reader.GetOrdinal("Descripcion")))
                    Descripcion = (System.String)reader["Descripcion"];
                if (!reader.IsDBNull(reader.GetOrdinal("OnClick")))
                    OnClick = (System.String)reader["OnClick"];
                if (!reader.IsDBNull(reader.GetOrdinal("OnOver")))
                    OnOver = (System.String)reader["OnOver"];
                if (!reader.IsDBNull(reader.GetOrdinal("OnOut")))
                    OnOut = (System.String)reader["OnOut"];
            }
        }


        protected void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE RIBBONMENU set "); strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); strCommand.Append(",idUsuarioModificacion=\"" + this.idUsuarioModificacion.ToString() + "\"");

            strCommand.Append(",orden='" + this.orden.ToString() + "'");
            strCommand.Append(",idParent='" + this.idParent.ToString() + "'");
            strCommand.Append(",inOrb='" + Convert.ToInt16(inOrb) + "'");
            strCommand.Append(",Caption=\"" + WLMFunctions.comillas(Caption) + "\"");
            strCommand.Append(",Icono=\"" + WLMFunctions.comillas(Icono) + "\"");
            strCommand.Append(",Relacion=\"" + WLMFunctions.comillas(Relacion) + "\"");
            strCommand.Append(",Descripcion=\"" + WLMFunctions.comillas(Descripcion) + "\"");
            strCommand.Append(",OnClick=\"" + WLMFunctions.comillas(OnClick) + "\"");
            strCommand.Append(",OnOver=\"" + WLMFunctions.comillas(OnOver) + "\"");
            strCommand.Append(",OnOut=\"" + WLMFunctions.comillas(OnOut) + "\"");
            strCommand.Append(" WHERE id='" + this.id + "'");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion
    }

    public class RibbonMenuCollection
    {

        private List<RibbonMenu> _items;
        public List<RibbonMenu> Elementos { get; set; }
        public RibbonMenuCollection()
        {
        }
        public RibbonMenuCollection(ref dbConnector ConexionDB)
        {

            string strCommand = "SELECT id FROM RIBBONMENU ";
            OdbcDataReader dataReader = ConexionDB.ExecuteReader(strCommand);
            Elementos = new List<RibbonMenu>();
            while (dataReader.Read())
            {
                RibbonMenu newItem = new RibbonMenu(Convert.ToInt32(dataReader["id"]), ref ConexionDB);
                Elementos.Add(newItem);
            }
            dataReader.Close();
            dataReader.Dispose();
        }
    }
}
